package com.jinke.api.handle;

import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

@Component
@org.apache.ibatis.type.MappedTypes(List.class)
@org.apache.ibatis.type.MappedJdbcTypes(JdbcType.VARCHAR)
public class StringListTypeHandler implements TypeHandler<List<String>> {

    private static final String DELIMITER = ",";

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> strings, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, String.join(DELIMITER, strings));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String s) throws SQLException {
        return Arrays.asList(resultSet.getString(s).split(DELIMITER));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int i) throws SQLException {
        return Arrays.asList(resultSet.getString(i).split(DELIMITER));
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int i) throws SQLException {
        return Arrays.asList(callableStatement.getString(i).split(DELIMITER));
    }
}

